<?php


namespace app\middleware;


use app\service\BucketLimiter;
use app\service\RateLimit;
use Webman\Http\Request;
use Webman\Http\Response;
use Webman\MiddlewareInterface;

class LimitingMiddleware implements MiddlewareInterface
{

    /**
     * 节流操作
     * @param Request $request
     * @param callable $handler
     * @return Response
     */
    public function process(Request $request, callable $handler): Response
    {
        $app = $request->app;
        $controller_data = explode("\\", $request->controller);
        if ($app) {
            $controller = $controller_data[3];
        } else {
            $controller = $controller_data[2];
        }
        $controllerArray = ['Login'];
        if (!in_array($controller, $controllerArray)) {
            $accessToken = $request->header('Access-Token');
            if ($accessToken) {
                //节流操作
                $rate = RateLimit::minLimit($accessToken);
                if ($rate) {
                    return json(['code' => 1, 'msg' => $rate]);
                }
                //漏桶算法 requierdToken访问的次数
                $rt = BucketLimiter::getLeakyBucketToken(1, $accessToken);
                if (isset($rt['code'])) {
                    return json($rt);
                }
            }
        }
        return $handler($request);
    }
}
